from agile.models import Project, Sprint, Task, TaskSearchCriteria, Scrum, Comment, Repository, Revision
from django import forms
from django.forms import widgets
from django.contrib.admin.widgets import FilteredSelectMultiple
from django.contrib.auth.models import User

class ProjectForm(forms.ModelForm):
    
    def __init__(self, *args, **kwargs):
        if 'read_only' in kwargs:
            read_only = kwargs.pop('read_only')
        else:
            read_only = False
            
        super(ProjectForm, self).__init__(*args, **kwargs)
        
        self.fields['completionDate'].label = 'Completion Date'
        
        if read_only:
            for field in self.fields:
                self.fields[field].widget.attrs['disabled'] = True
        
    class Meta:
        model = Project
        widgets = {
            'completionDate': widgets.TextInput(attrs={'class':'datepicker'}),
        }

            
class SprintForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        if 'read_only' in kwargs:
            read_only = kwargs.pop('read_only')
        else:
            read_only = False
        super(SprintForm, self).__init__(*args, **kwargs)
        self.fields['startDate'].label = 'Start Date'
        self.fields['endDate'].label = 'End Date'
        self.fields['users'].help_text = ''
        self.fields['users'].label = ''
        
        if read_only:
            for field in self.fields:
                self.fields[field].widget.attrs['disabled'] = True
                
    class Meta:
        model = Sprint
        widgets = {
            'endDate': widgets.TextInput(attrs={'class':'datepicker'}),
            'startDate': widgets.TextInput(attrs={'class':'datepicker'}),
            'users': FilteredSelectMultiple('Users', False),
        }
        
    class Media:
        css = {
            'all':['/static/admin/css/widgets.css'],
        }
        js = ['/static/admin/js/jsi18n/']


   
class TaskForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        if 'read_only' in kwargs:
            read_only = kwargs.pop('read_only')
        else:
            read_only = False
            
        super(TaskForm, self).__init__(*args, **kwargs)
        if 'instance' in kwargs:
            instance = kwargs.pop('instance')
            self.fields['revisions'].queryset = Revision.objects.filter(repo__project=instance.project).order_by('-number')
            self.fields['parent'].queryset = Task.objects.filter(project=instance.project, parent = None)
        else:
            self.fields['revisions'].queryset = Revision.objects.none()
            self.fields['parent'].queryset = Task.objects.none()
        
        if read_only:
            for field in self.fields:
                self.fields[field].widget.attrs['disabled'] = True
    class Meta:
        model = Task
        widgets = {
            'description': widgets.Textarea(attrs={'cols':60,'rows':8}),
            'users': FilteredSelectMultiple('Users',False),
        }
    
    class Media:
        css = {
            'all':['/static/admin/css/widgets.css'],
        }
        js = ['/static/admin/js/jsi18n/']

class ScrumForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        if 'read_only' in kwargs:
            read_only = kwargs.pop('read_only')
        else:
            read_only = False
            
        super(ScrumForm, self).__init__(*args, **kwargs)
       
        if read_only:
            for field in self.fields:
                self.fields[field].widget.attrs['disabled'] = True
                       
    class Meta:
        model = Scrum
        widgets ={
            'time': widgets.TextInput(attrs={'class':'timepicker'}),
            'day': widgets.Select(choices=[('6', 'Sunday'), ('0', 'Monday'), ('1', 'Tuesday'), ('2', 'Wednesday'), ('3', 'Thursday'),
                                           ('4', 'Friday'), ('5', 'Saturday')]),
        }



class CommentForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(CommentForm, self).__init__(*args, **kwargs)

    class Meta:
        model = Comment
        exclude = ('user', 'tasks', 'time',)

class CommentDeleteForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(CommentDeleteForm, self).__init__(*args, **kwargs)

        self.fields['user'].widget.attrs['disabled'] = True
        self.fields['tasks'].widget.attrs['disabled'] = True
        self.fields['time'].widget.attrs['disabled'] = True
        self.fields['contents'].widget.attrs['disabled'] = True

    class Meta:
        model = Comment

class TaskSearchCriteriaForm(forms.ModelForm):    
    def __init__(self, *args, **kwargs):
        super(TaskSearchCriteriaForm, self).__init__(*args, **kwargs)
        
    class Meta:
        model = TaskSearchCriteria
        exclude = ('owner',)
        
class ProjectSearchCriteriaForm(forms.Form):
    name = forms.CharField(max_length=256)
    
    def get_param_dict(self):
        retval = dict()
        if 'name' in self.data != None and len(self.data['name']) > 0:
            retval['name__icontains'] = self.data['name']
        return retval

class SprintSearchCriteriaForm(forms.Form):
    name = forms.CharField(max_length=256)
    project = forms.ModelChoiceField(queryset=Project.objects.all())

    def get_param_dict(self):
        retval = dict()
        if 'name' in self.data and len(self.data['name']) > 0:
            retval['name__icontains'] = self.data['name']
        if 'project' in self.data and len(self.data['project']) > 0:
            retval['project__id'] = self.data['project']
        return retval


class RepositoryForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        if 'read_only' in kwargs:
            read_only = kwargs.pop('read_only')
        else:
            read_only = False
        super(RepositoryForm, self).__init__(*args, **kwargs)
        if read_only:
            for field in self.fields:
                self.fields[field].widget.attrs['disabled'] = True
    
    class Meta:
        model = Repository

class RepositorySearchCriteriaForm(forms.Form):
    name = forms.CharField(max_length=256)
    project = forms.ModelChoiceField(queryset=Project.objects.all())
    
    def get_param_dict(self):
        retval = dict()
        if 'name' in self.data and len(self.data['name']) > 0:
            retval['name__icontains'] = self.data['name']
        if 'project' in self.data and len(self.data['project']) > 0:
            retval['project__id'] = self.data['project']
        return retval

class UserUsernameForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):          
        user =  kwargs.pop('instance')      
        self.user = user
        super(UserUsernameForm, self).__init__(*args, **kwargs)
        
    class Meta:
        model = User
        #exclude =('user','first_name','last_name','email')
        fields = ("username",)
    
    def save(self):
        username = self.cleaned_data['username']
        self.user.username = username     
        self.user.save()        
        return self.user
    
class UserFirstnameForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):          
        user =  kwargs.pop('instance')      
        self.user = user
        super(UserFirstnameForm, self).__init__(*args, **kwargs)
        
    class Meta:
        model = User
        #exclude =('user','username','last_name','email', 'id', 'password', 'is_staff','is_active','is_superuser', 
        #          'last_login', 'date_joined','groups', 'user_permissions' )
        fields = ("first_name",)
         
    
    
    def save(self):
        first_name = self.cleaned_data['first_name']
        self.user.first_name = first_name     
        self.user.save()        
        return self.user   
  
  
class UserLastnameForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):          
        user =  kwargs.pop('instance')      
        self.user = user
        super(UserLastnameForm, self).__init__(*args, **kwargs)
        
    class Meta:
        model = User
        exclude =('user','username','first_name','email', 'id', 'password', 'is_staff','is_active','is_superuser', 
                  'last_login', 'date_joined','groups', 'user_permissions')
    def save(self):
        last_name = self.cleaned_data['last_name']
        self.user.last_name = last_name     
        self.user.save()        
        return self.user
    
class UserEmailForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):          
        user =  kwargs.pop('instance')      
        self.user = user
        super(UserEmailForm, self).__init__(*args, **kwargs)
        
    class Meta:
        model = User
        exclude =('user','username','last_name','first_name', 'id', 'password', 'is_staff','is_active','is_superuser', 
                  'last_login', 'date_joined','groups', 'user_permissions')
    
    def save(self):
        email = self.cleaned_data['email']
        self.user.email = email     
        self.user.save()        
        return self.user
